//
//  HomeLiveReccomendViewController.m
//  CYWFrame
//
//  Created by 于顺燊 on 2018/8/15.
//  Copyright © 2018年 Macx. All rights reserved.
//

#import "HomeLiveReccomendViewController.h"
#import "LiveCollectionViewCell.h"
//#import "LiveRoomViewController.h"
#import "LiveRoomViewControllerAudience.h"

#import "TCPlayViewController.h"
#import "TCPlayViewController_LinkMic.h"

#import "AdsServer.h"
#import "Live.h"

@interface HomeLiveReccomendViewController () <UICollectionViewDelegate, UICollectionViewDataSource,  LiveRoomVCADelegate>


@property (nonatomic, assign) NSInteger page; // 网络请求页数
@property (nonatomic, strong) NSMutableArray *infoArr;

@property (nonatomic, retain) TCPlayViewController *playVC;
@property (nonatomic, retain) LiveRoomViewControllerAudience *liveRoomVCAudience;

@property (nonatomic, strong) NSString *keyWord;
@property (nonatomic, assign) NSInteger isPush;

//AgoraLive
@property (assign, nonatomic) AgoraVideoProfile videoProfile;
@property (assign, nonatomic) AgoraClientRole clientRole;


@end

@implementation HomeLiveReccomendViewController {
	BOOL             _hasEnterplayVC; // 直播间
	XRCarouselView  *_carouselView;
	
	UICollectionView *_collectionView;
	LiveCollectionViewCell *_item;
	
	UILabel     *_noThings;
}

- (void)viewWillAppear:(BOOL)animated {
	self.isPush = 0;
	
	if (self.isSearch) {
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchLive:)name:@"searchLive" object:nil];
	}
	else {
		[self GETLives];
	}
}

- (void)viewDidAppear:(BOOL)animated {
	_playVC = nil;
	_hasEnterplayVC = NO;
}


- (void)viewDidDisappear:(BOOL)animated {
	//    [self.navigationController popViewControllerAnimated:YES];
	if (self.isSearch && self.isPush == 0) {
		[[NSNotificationCenter defaultCenter] removeObserver:self name:@"searchLive" object:nil];
	}
}

// 主页tableView是否滚动接收到通知
- (void)searchLive:(NSNotification *)notification {
	self.keyWord = notification.userInfo[@"keyWord"];
	
	NSLog(@"－－－－－直播搜索接收到通知------\n = %@", self.keyWord);
	//    _noThings.hidden = YES;
	[self GETLives];
}

- (void)viewDidLoad {
	[super viewDidLoad];
	// Do any additional setup after loading the view.
	
	self.videoProfile = AgoraVideoProfileLandscape480P;
	self.clientRole = AgoraClientRoleAudience;
	self.keyWord = @"";
	self.page = 1;
	
	[self buildUI];
	
	if (!self.isSearch) {
		[self GETLives];
		[self GETAds];
	}
	
	
	//    [self GETLives];
	
	
	
	[self refreshData];
	
}

#pragma mark ==========构建UI==========
- (void)buildUI {
	
	self.view.backgroundColor = kWhiteColor;
	
	_carouselView = [[XRCarouselView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SW(5)*2)];
	//    [_scrollView addSubview:_carouselView];
	_carouselView.contentMode = UIViewContentModeScaleAspectFill;
	_carouselView.imageArray = @[IMAGE(@"img.jpg")];
	_carouselView.time = 2;
	
	
	// 集合视图 collectionView所有布局的父类
	// 系统提供自带的布局类
	UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
	// 默认为纵向滑动
	flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
	flowLayout.minimumInteritemSpacing = 0;
	flowLayout.minimumLineSpacing = 0;
	
	// 创建collectionView
	_collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 1, SCREEN_WIDTH, self.view.height-64-49-44-10) collectionViewLayout:flowLayout];
	[self.view addSubview:_collectionView];
	_collectionView.backgroundColor = kWhiteColor;
	_collectionView.delegate = self;
	_collectionView.dataSource = self;
	
	[_collectionView registerNib:[UINib nibWithNibName:@"LiveCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"item"];
	
	/*
	if (self.isSearch) {
		_collectionView.frame = CGRectMake(0, 1, SCREEN_WIDTH, SCREEN_HEIGHT-64-44-(1+3*SW(20)));
		flowLayout.headerReferenceSize = CGSizeMake(0, 0);
	}
	else
		flowLayout.headerReferenceSize = CGSizeMake(0, SW(5)*2+10);
	//注册头视图
	[_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionViewHeader"];
	
	*/
	_noThings = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-(65+SW(20)*3))];
	[self.view addSubview:_noThings];
	_noThings.text = @"没有相关资源";
	_noThings.textAlignment = NSTextAlignmentCenter;
	_noThings.backgroundColor = self.view.backgroundColor;
	_noThings.hidden = YES;
	
	
}

#pragma mark ==========UICollectionView==========
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
	
	_item = [collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
	
	_item.model = self.infoArr[indexPath.row];
	
	return _item;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
	return self.infoArr.count;
}
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
	//    NSLog(@"%f", _item.cover.height);
	return CGSizeMake(SW(2), SW(2));
}
//定义每个UICollectionView 的 margin
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
	return UIEdgeInsetsMake(0, 0, 0, 0);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
	
	NSLog(@"点击collectionView.item = %ld", indexPath.row);
	
	Live *model = self.infoArr[indexPath.row];
	
	[self PUTLive:[model.anchor valueForKey:@"user_id"]];
	
}
//创建头视图
/*
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
		   viewForSupplementaryElementOfKind:(NSString *)kind
								 atIndexPath:(NSIndexPath *)indexPath {
	
	UICollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionViewHeader" forIndexPath:indexPath];
	if (!self.isSearch) {
		[headView addSubview:_carouselView];
	}
	headView.backgroundColor = UISeparatedColorRGB;
	
	return headView;
}
*/

#pragma mark ==========更新数据==========
- (void)refreshData {
	__weak typeof (self) weakSelf = self;
	
	_collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
		NSLog(@"下拉刷新");
		weakSelf.page = 1;
		[weakSelf GETLives];
	}];
	
	_collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
		NSLog(@"上拉加载");
		weakSelf.page++;
		[weakSelf GETLives];
	}];
	
}


#pragma mark ===========响应方法==========
- (void)GETLives {
	
	//GET /lives 获取直播列表 ? page 页码 tag_id 分类ID per_page 每页显示数 keyword 关键词 支持直播标题
	
	NSDictionary *param;
	
	if (self.isSearch) {
		if (self.keyWord.length == 0) {
			[_collectionView.mj_header endRefreshing];
			[_collectionView.mj_footer endRefreshing];
			return;
		}
		param = @{@"page":[NSString stringWithFormat:@"%ld", self.page],
				  @"per_page":@"10",
				  @"keyword":self.keyWord};
	}
	else {
		param = @{@"page":[NSString stringWithFormat:@"%ld", self.page],
				  @"per_page":@"10",
				  @"tag_id":self.tagId};
	}
	
	[[NetworkTool sharedTool] requestWithName:@"获取直播" URLString:APILives parameters:param method:@"GET" callBack:^(id responseObject) {
		
		NSArray *arr = responseObject[@"data"];
		
		if (self.page == 1) {
			[self.infoArr removeAllObjects];
		}
		
		_noThings.hidden = YES;
		if (arr.count == 0) {
			self.page--;
			if (self.page == 0) {
				self.page = 1;
			}
			
			// 所有的逻辑显示
			if (self.isSearch) {
				[_collectionView.mj_footer endRefreshing];
				//                [MBProgressHUD hideHUDForView:self.view animated:YES];
				//                [LZCTools HUDMessage:@"没有这个直播" delay:1.5f];
				if (self.infoArr.count == 0) {
					_noThings.hidden = NO;
				}
			}
		}
		
		for (NSDictionary *dic in arr) {
			Live *model = [[Live alloc] init];
			[model setValuesForKeysWithDictionary:dic];
			[self.infoArr addObject:model];
		}
		
		dispatch_async(dispatch_get_main_queue(), ^{
			[MBProgressHUD hideHUDForView:self.view animated:YES];
			[_collectionView.mj_header endRefreshing];
			[_collectionView.mj_footer endRefreshing];
			[_collectionView reloadData];
		});
		
	}];
}

// 获取广告
- (void)GETAds {
	
	[AdsServer GETAds:@{@"board":@"app_live"} xrView:_carouselView];
	
}

/**
 进入直播间
 */
- (void)PUTLive:(NSString *)userId {
	
	if (GetUserDefaule(USERINFO) == NULL) {
		[self presentViewController:[LZCTools alertMessage:@"请先登录"]animated:YES completion:nil];
		return;
	}
	
	// PUT /users/{uid}/lives 进入直播间 只有主播进入都会有推流地址 uid * 主播ID
	NSString *url = [APIUser stringByAppendingFormat:@"/%@/lives", userId];
	
	[[NetworkTool sharedTool] requestWithName:@"进入直播间" URLString:url parameters:nil method:@"PUT" callBack:^(id responseObject) {
		
		if ([[GetUserDefaule(USERINFO) valueForKey:@"user_id"] isEqualToString:userId]) {
			NSLog(@"这个直播是自己的直播，走创建直播流程");
			self.clientRole = AgoraClientRoleBroadcaster;
		}
		
		Live *model = [[Live alloc] init];
		[model setValuesForKeysWithDictionary:[responseObject valueForKey:@"data"]];
		
		
		TCLiveInfo *info = [[TCLiveInfo alloc] init];
		info.userinfo = [[TCLiveUserInfo alloc] init];
		
		info.userid = [model.anchor valueForKey:@"user_id"];
		info.groupid = model.chatroom_id;
		info.likecount = [model.like_num intValue];
		info.title = model.title;
		//        info.playurl = model.pull_url[0]; // rtmp 默认第一个
		info.playurl = [model.pull_multi_urls valueForKey:@"rtmp_lsd"]; //拉流地址，键名后缀代表清晰度，无则代表原画 lud-超清 lhd-高清 lsd-标清 lld-流畅，如rtmp_lud:’rtmp://xxx’,代表超清的rtmp 默认标清，切换超清
		info.biaoUrl = [model.pull_multi_urls valueForKey:@"rtmp_lsd"];
		info.gaoUrl = [model.pull_multi_urls valueForKey:@"rtmp_lud"];
		info.timestamp = [model.start_time intValue];
		info.userinfo.nickname = [model.anchor valueForKey:@"nickname"];
		info.userinfo.headpic = [model.anchor valueForKey:@"face"];
		info.userinfo.frontcover = [model.anchor valueForKey:@"face"];
		info.isLike = [NSString stringWithFormat:@"%@", [model.anchor valueForKey:@"is_like"]];
		//        info.money = [model.anchor valueForKey:@"money"];
		info.money = [NSString stringWithFormat:@"%ld", model.stars_count];
		info.isPraise = [NSString stringWithFormat:@"%ld", model.is_like];
		
		info.viewercount = (int)model.viewer_num;
		info.roomid = [NSString stringWithFormat:@"%ld", (long)model.liveId];
		
		//        info.isVip = [self.liveData[@"anchor"] valueForKey:@"is_enterprise"];
		
		info.isVip = [NSString stringWithFormat:@"%@", [model.anchor valueForKey:@"role"]];
		info.myuserid = [model.anchor valueForKey:@"user_id"];
		
		
		// 保存直播信息，后面用到
		NSDictionary *live = @{@"hostId":info.userid, @"groupId":info.groupid};
		SetUserDefaule(live, CURRLIVE);
		
		NSDictionary *userinfo = GetUserDefaule(USERINFO);
		
		NSDictionary *infoDict = @{@"imId":[userinfo valueForKey:@"user_id"],
								   @"uid":[userinfo valueForKey:@"user_id"],
								   @"nickname":[userinfo valueForKey:@"nickname"],
								   @"headpic":[userinfo valueForKey:@"face"],
								   @"level":[NSString stringWithFormat:@"%@", [userinfo valueForKey:@"level"]]};
		
		
		NSError *parseError = nil;
		NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict options:NSJSONWritingPrettyPrinted error:&parseError];
		NSString *infoStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
		
		info.senderInfo = infoStr;
		
		// MARK: 打开播放界面
		/*
		 if (_playVC == nil) {
		 _playVC = [[TCPlayViewController_LinkMic alloc] initWithPlayInfo:info videoIsReady:^{
		 if (!_hasEnterplayVC) {
		 self.isPush = 1;
		 [self.navigationController pushViewController:_playVC animated:YES];
		 _hasEnterplayVC = YES;
		 }
		 }];
		 }
		 */
		
		if (_liveRoomVCAudience == nil) {
			UIStoryboard *agoraSB = [UIStoryboard storyboardWithName:@"AgoraLive" bundle:nil];
			_liveRoomVCAudience = (LiveRoomViewControllerAudience *)[agoraSB instantiateViewControllerWithIdentifier:@"AgoraLiveRoomVCA"];
			if (!_hasEnterplayVC && _liveRoomVCAudience) {
				self.isPush = 1;
				_liveRoomVCAudience.channelId = info.groupid;
				_liveRoomVCAudience.clientRole = self.clientRole;
				_liveRoomVCAudience.videoProfile = self.videoProfile;
				_liveRoomVCAudience.delegate = self;
				_liveRoomVCAudience.liveInfo = info;
				[self.navigationController pushViewController:_liveRoomVCAudience animated:YES];
				_hasEnterplayVC = YES;
			}
		}
		
		[self performSelector:@selector(enterPlayVC:) withObject:_liveRoomVCAudience afterDelay:0.5];
		
	}];
}

-(void)enterPlayVC:(NSObject *)obj{
	if (!_hasEnterplayVC) {
		self.isPush = 1;
		[self.navigationController pushViewController:_liveRoomVCAudience animated:YES];	//这行的VC也改了，到时候要回滚的时候记得改过来
		_hasEnterplayVC = YES;
	}
}

//MARK: - AgoraLive delegates

- (void)liveVCNeedClose:(LiveRoomViewControllerAudience *)liveVC {
	//[self dismissViewControllerAnimated:YES completion:nil];
	[self.navigationController popViewControllerAnimated:YES];
	_hasEnterplayVC = NO;
	_liveRoomVCAudience = nil;
	self.clientRole = AgoraClientRoleAudience;
}


// 懒加载
- (NSMutableArray *)infoArr {
	if (_infoArr == nil) {
		_infoArr = [[NSMutableArray alloc] init];
	}
	return _infoArr;
}

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
